//设置的温湿度阈值
var min_temp = 0
var max_temp = 0
var min_humi = 0
var max_humi = 0
//温湿度初始值
var temp_val = 0 + '℃'
var humi_val = 0 + '%'
//初始化状态
var fan_status = "close"
var drip_status = "close"
var roller_shutter_status = "close"
//初始化模式
var fan_mode = "manual"
var drip_mode = "manual"
var roller_shutter_mode = "manual"
//星期数组
var week_array = ["日", "一", "二", "三", "四", "五", "六"]
//定时器对象
var timeID;
//订阅的主题
var topic1 = 'SENSOR'
var topic2 = 'CTRL'

// 连接选项
const options = {
    clean: true, // true: 清除会话, false: 保留会话
    connectTimeout: 4000, // 超时时间
    // 认证信息
    clientId: 'yzj_test',
    username: 'yzj_test',
    password: 'yzj_test',
}

//设置MQTT连接的地址
const connectUrl = 'ws://www.dataswap.work:8083'
//连接MQTT
const client = mqtt.connect(connectUrl, options)

function load_func() {
    //设置的温湿度阈值
    min_temp = document.getElementById("min_temp").value = min_temp
    max_temp = document.getElementById("max_temp").value = max_temp
    min_humi = document.getElementById("min_humi").value = min_humi
    max_humi = document.getElementById("max_humi").value = max_humi
    //初始化状态
    fan_status = document.getElementById("fan_status").value = fan_status
    drip_status = document.getElementById("drip_status").value = drip_status
    roller_shutter_status = document.getElementById("roller_shutter_status").value = roller_shutter_status
    //开启一个延时函数
    timeID = setTimeout("loadtime()", 0);
}

//定时器函数(每隔1秒执行一次)
function loadtime() {
    var str = "";
    //获取一个Date对象
    var time = new Date();
    str += time.getFullYear();
    str += "年";
    str += time.getMonth() + 1;
    str += "月";
    str += time.getDate();
    str += "日 ";
    str += time.getHours();
    str += "时";
    str += time.getMinutes();
    str += "分";
    str += time.getSeconds();
    str += "秒 ";
    str += "星期";
    str += week_array[time.getDay()]
    //将str写入label标签中，用以显示时间
    time_now = document.getElementById("time_now").innerText = str;
    //每隔3秒发布一次get_data
    if (time.getSeconds() % 3 == 0)
        client.publish(topic2, "get_data");
    //开启一个延时函数
    timeID = setTimeout("loadtime()", 1000);
}

function getXMLHttpRequest() {
    var xmlhttp = null;
    if (window.XMLHttpRequest)//自动检测当前浏览器的版本，如果是 IE5.0 以上的高版本的浏览器
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();//创建请求对象
    }
    else////如果浏览器是底版本的
    {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//创建请求对象
    }
    return xmlhttp;//返回请求对象
}

//1、创建对象
var xmlHttp = getXMLHttpRequest();

//2、设置回调函数
xmlHttp.onreadystatechange = function () {
    // console.log('xmlHttp.readyState==' + xmlHttp.readyState + ' ' + 'xmlHttp.status==' + xmlHttp.status)
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        //获取服务器的应答（假如服务器的应答是字符串格式）
        var ret = xmlHttp.responseText;
        // console.log(ret)
        if (ret == '0') {
            // console.log("数据插入成功")
        }
        else if (ret == '1') {
            console.log('数据库初始化失败')
        }
        else if (ret == '2') {
            console.log('数据库初始化连接失败')
        }
    }
}

client.on('reconnect', (error) => {
    connect_status = document.getElementById("connect_status").innerText = "正在连接"
    console.log('正在重连:', error)
})

client.on('error', (error) => {
    connect_status = document.getElementById("connect_status").innerText = "连接失败"
    console.log('连接失败:', error)
})

client.on('message', (topic, message) => {
    let info = message.toString().split(",")
    // let info = "get_data,20,30,40,60,26,55,close,open,auto,manual".split(",")
    // get_data, 20, 30, 40, 60, 26, 55, close, open, auto, manual
    console.log('收到消息：', topic, message.toString())
    if ((topic == topic1) && (info[0] == 'get_data')) {
        //更新信息
        min_temp = info[1]
        max_temp = info[2]
        min_humi = info[3]
        max_humi = info[4]
        temp_val = info[5] + "℃"
        humi_val = info[6] + "%"
        fan_status = info[7]
        drip_status = info[8]
        fan_mode = info[9]
        drip_mode = info[10]

        //阈值
        document.getElementById("min_temp").value = min_temp
        document.getElementById("max_temp").value = max_temp
        document.getElementById("min_humi").value = min_humi
        document.getElementById("max_humi").value = max_humi

        //当前值
        document.getElementById("temp_val").innerText = temp_val
        document.getElementById("humi_val").innerText = humi_val
        //状态
        document.getElementById("fan_status").value = fan_status
        document.getElementById("drip_status").value = drip_status
        //工作模式
        document.getElementById("fan_mode").value = fan_mode
        document.getElementById("drip_mode").value = drip_mode
        //刷新页面模式
        flash_mode()

        //创建请求 GET方式 异步
        var url = "/cgi-bin/data_insert.cgi?";
        url += message.toString();
        // console.log(url)
        xmlHttp.open("GET", url, true);
        //4、发送请求
        xmlHttp.send();
    }
})

// 成功连接后触发的回调
client.on('connect', () => {
    connect_status = document.getElementById("connect_status").innerText = "连接成功"
    console.log('MQTT connect success');
    // 订阅主题，这里可以订阅多个主题
    client.subscribe([topic1, topic2], () => {
        console.log(`订阅了主题 ${[topic1, topic2].join('和')}`)
        client.publish(topic2, 'get_data');
        console.log('get_data')
    })
})

//下发命令函数
function setting_btn() {
    // topic1
    let msg = 'set_data,' + min_temp + ',' + max_temp + ',' + min_humi + ',' + max_humi + ',' + fan_mode + ',' + drip_mode
    alert('下发成功')
    client.publish(topic2, msg);
}

function fan_status_btn() {
    if (fan_status == 'close') {
        fan_status = 'open'
        client.publish(topic2, 'set_temp_adjust=' + fan_status)
        document.getElementById("fan_status").value = fan_status
    }
    else if (fan_status == 'open') {
        fan_status = 'close'
        client.publish(topic2, 'set_temp_adjust=' + fan_status)
        document.getElementById("fan_status").value = fan_status
    }

}
function drip_status_btn() {
    if (drip_status == 'close') {
        drip_status = 'open'
        client.publish(topic2, 'set_humi_adjust=' + drip_status)
        document.getElementById("drip_status").value = drip_status
    }
    else if (drip_status == 'open') {
        drip_status = 'close'
        client.publish(topic2, 'set_humi_adjust=' + drip_status)
        document.getElementById("drip_status").value = drip_status
    }
}

function roller_shutter_status_btn() {
    if (roller_shutter_status == 'close') {
        roller_shutter_status = 'open'
        document.getElementById("roller_shutter_status").value = roller_shutter_status
    }
    else if (roller_shutter_status == 'open') {
        roller_shutter_status = 'close'
        document.getElementById("roller_shutter_status").value = roller_shutter_status
    }
}

//刷新模式函数
function flash_mode() {
    if (fan_mode == 'auto') {
        document.getElementById("fan_status").disabled = true
    } else if (fan_mode == 'manual') {
        document.getElementById("fan_status").disabled = false
    }

    if (drip_mode == 'auto') {
        document.getElementById("drip_status").disabled = true
    } else if (drip_mode == 'manual') {
        document.getElementById("drip_status").disabled = false
    }

    if (roller_shutter_mode == 'auto') {
        document.getElementById("roller_shutter_status").disabled = true
    } else if (roller_shutter_mode == 'manual') {
        document.getElementById("roller_shutter_status").disabled = false
    }

}


function fan_mode_btn() {
    if (fan_mode == 'auto') {
        fan_mode = 'manual'
        document.getElementById("fan_mode").value = fan_mode
    } else if (fan_mode == 'manual') {
        fan_mode = 'auto'
        document.getElementById("fan_mode").value = fan_mode
    }
    flash_mode()
}

function drip_mode_btn() {
    if (drip_mode == 'auto') {
        drip_mode = 'manual'
        document.getElementById("drip_mode").value = drip_mode
    } else if (drip_mode == 'manual') {
        drip_mode = 'auto'
        document.getElementById("drip_mode").value = drip_mode
    }
    flash_mode()
}


function roller_shutter_mode_btn() {
    if (roller_shutter_mode == 'auto') {
        roller_shutter_mode = 'manual'
        document.getElementById("roller_shutter_mode").value = roller_shutter_mode
    } else if (roller_shutter_mode == 'manual') {
        roller_shutter_mode = 'auto'
        document.getElementById("roller_shutter_mode").value = roller_shutter_mode
    }
    flash_mode()
}

